package br.ucb.musicbay.conversor;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

import br.ucb.musicbay.genero.Genero;
import br.ucb.musicbay.genero.GeneroBO;

@FacesConverter(value = "generoConversor", forClass = Genero.class)
public class GeneroConversor implements Converter {

	@Override
	public Object getAsObject(FacesContext context, UIComponent component, String value) throws ConverterException {
		Genero genero = new Genero();
		if (value != null && value.trim().length() > 0) {
			Integer id = Integer.valueOf(value);
			try {
				GeneroBO generoBO = new GeneroBO();
				genero = generoBO.recoverById(id);
			} catch (Exception e) {
				throw new ConverterException("Nao Foi possivel encontrar a categoria de codigo" + value + "." + e.getMessage());
			}
		}
		return genero;
	}

	@Override
	public String getAsString(FacesContext context, UIComponent component, Object object) throws ConverterException {
		if (object != null) {
			Genero genero = (Genero) object;
			return genero.getIdgenero().toString();
		}
		return null;
	}

}
